package com.jin.webvideo.base.dc.safe.whitelist;

import com.jin.webvideo.base.dc.KeyValuePairReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 允许使用的类/包白名单
 *
 * @author biao532
 * @date 2023/12/03 11:28
 **/
public class ClassWhitelist implements Whitelist<String>{
    private static final String SUFFIX_PACKAGE = ".*";
    private SetWhitelist<String> pkgNameSet;
    private SetWhitelist<String> clsNameSet;
    public ClassWhitelist(InputStream stream) throws IOException {
        pkgNameSet = new SetWhitelist<>();
        clsNameSet = new SetWhitelist<>();
        read(stream);
    }
    protected void read(InputStream inputStream) throws IOException {
        KeyValuePairReader reader = new KeyValuePairReader(new InputStreamReader(inputStream));
        String line = null;
        while (null != (line = reader.readLine()) ) {
            if (isPackage(line)) {
                pkgNameSet.add(packageName(line));
                continue;
            }
            clsNameSet.add(line);
        }
    }

    @Override
    public int size() {
        return pkgNameSet.size() + clsNameSet.size();
    }

    @Override
    public boolean contains(String o) {
        return pkgNameSet.contains(packageName(o)) || clsNameSet.contains(o);
    }

    private boolean isPackage(String line) {
        return line.endsWith(ClassWhitelist.SUFFIX_PACKAGE);
    }

    private static String packageName(String line) {
        int idx = line.lastIndexOf(".");
        if (idx == -1) {
            return line;
        }
        if (idx == 0) {
            throw new IllegalArgumentException(String.format("不合法的类名[%s]", line));
        }
        return line.substring(0, idx);
    }
}
